package com.deva.bletest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice; 
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;  
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {

	/**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
     * will keep every loaded fragment in memory. If this becomes too memory
     * intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    /* 涓嬭浇涓� */
	private static final int FIRMDOWNLOAD = 1;
	/* 涓嬭浇缁撴潫 */
	private static final int FIRMDOWNLOAD_FINISH = 2;
	//
    ViewPager mViewPager;
    Context mContext;
	
    public static final String BMS_Settings="bms_setting";
	public static final String APP_UPDATETHIS="app_updatethis";
	public static final String EXTRAS_DEVICE_TYPE = "DEVICE_TYPE";
	public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";	
	public static final String APP_USER_CODE = "USER_CODE";
	
    private final static String TAG = MainActivity.class.getSimpleName();
    
	//private BluetoothAdapter blueadapter=null;
    private boolean mDeviceConnected=false;
    private boolean updateThis=false;
	//private boolean hasregister=false;
	
	private boolean hasconnected=false;
	private boolean begincmd=false;
	
	private boolean needUpdate=false;
	private boolean retUpdate=false;
	
	UpdateManager manager = new UpdateManager(MainActivity.this);
	
	//private DeviceReceiver mydevice=new DeviceReceiver();

	//private List<String> deviceList=new ArrayList<String>();

	private BluetoothSocket bltSocket = null;
	private BluetoothDevice bltDevice = null;
	private BluetoothAdapter mBluetoothAdapter=null;
	private readThread mreadThread = null;
	int lastPageItem=-1; 
	int showCount=0;
	private clientThread clientConnectThread=null;
	//private String mDeviceName;
    private String mDeviceAddress;
    private int mDeviceType;
    private BluetoothLeService mBluetoothLeService;
    
    boolean connect_status_bit=false;
	boolean bBluetoothLeConnected=false;
	String mRevString="";
	
	public boolean g_bEnableResetBMS=true;
	public boolean g_bSupportPsw=false;
	public boolean g_bRemariMode=false;
	//
	private ProgressBar mProgress;
	private AlertDialog mUpdateFirmDialog;
	private int progress;
	private String mFirmWareFilePath;
	public int sendrepose;
	public boolean updatingfirmware=false;
	public boolean g_firmwareUpdating=false;
	private UpdateFirmwareThread firmwareUpdateTrhead;
	private EditText mPassword;
	public String pswString;
	protected boolean needReConnect=false;
	protected boolean bNewFirmware=false;
	protected String mHardwareStr="";
	
	 // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            bBluetoothLeConnected=false;
            if (mBluetoothLeService.initialize())
            {
            	// Automatically connects to the device upon successful start-up initialization.
                if(mBluetoothLeService.connect(mDeviceAddress))
                {
                	mDeviceConnected=true;
                	bBluetoothLeConnected=true;
                	clientConnectThread = new clientThread();  
                	clientConnectThread.start();
                }
            }
            else
            {
                Log.e("====TAG", "Unable to initialize Bluetooth");
                //finish();
            }

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {

		@Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                //mConnected = true;
            	connect_status_bit=true;
            	//
        	    //hasconnected=true;
        	    //begincmd=true;
        	    //bBluetoothLeConnected=false;
        	    //mDeviceConnected=true;
            }
            else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)){
            	connect_status_bit=false;
                Message msg = new Message();  
                msg.obj = getString(R.string.text_bmsdisconected);;  
                msg.what = -2;
                LinkDetectedHandler.sendMessage(msg);
                //
                //if(hasconnected)
                {
                	hasconnected=false;
                	begincmd=false;
                	//bBluetoothLeConnected=false;
                	//mDeviceConnected=false;
                }
            }
            else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                // Show all the supported services and characteristics on the user interface.
            	List<BluetoothGattService> gattServices=mBluetoothLeService.getSupportedGattServices();
            	if (gattServices != null)
            	{
	                if( gattServices.size()>0&&mBluetoothLeService.get_connected_status( gattServices )>=4 )
	                {
	        	        if( connect_status_bit )
	        			 {
	        				mBluetoothLeService.enable_JDY_ble(true);
	        				 try {  
	        			            Thread.currentThread();  
	        			            Thread.sleep(100);  
	        			        } catch (InterruptedException e) {  
	        			            e.printStackTrace();  
	        			        }  
	        				mBluetoothLeService.enable_JDY_ble(true);
	       				 	//
	                        Message msg = new Message();  
	                        msg.obj = getString(R.string.text_bmsconected);
	                        msg.what = 0;  
	                        LinkDetectedHandler.sendMessage(msg); 
	        			  }else{
	        				  //ConnectDevice();
	        				  //mDeviceConnected=true;
	        				  connect_status_bit=true;
	        				  Toast.makeText(MainActivity.this, getString(R.string.text_bmsunconected), Toast.LENGTH_LONG).show();
	        			  }
	                }
            	}
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
            	//Log.d(TAG,intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            	String rstr=intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
            	int i=rstr.indexOf("\r");
            	if(i>=0)
            	{
        			if(i>0) mRevString+=rstr.substring(0, i);
        			Message msg = new Message();  
        			msg.obj = mRevString;
        			msg.what = 1;
        			LinkDetectedHandler.sendMessage(msg);
	                mRevString=new String("");
            	}
            	else
            	{
            		i=rstr.indexOf("\n");
            		if(i>=0)
            		{
            			mRevString+=rstr.substring(i, rstr.length()-1);
            		}
            		else
            		{
            			mRevString+=rstr;
            		}
            	}
            }
        }
    };
    
	Handler timerHandler=new Handler();

	Runnable timerRunnable=new Runnable(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			String msgText;
			if(!updatingfirmware){
				//
				if(hasconnected)
				{
					int item=mViewPager.getCurrentItem();				
					//
					if(item!=lastPageItem)
					{
						//静态面面
						switch(item)
						{
						case 6:
							msgText="GTB";
							sendMessageHandle(msgText);
							break;
						case 7:
							msgText="GTY";
							sendMessageHandle(msgText);
							break;						
						default:break;
						}
					}
					//else
					{
						switch(item)
						{
							case 0:
								msgText="GTZ";
								sendMessageHandle(msgText);
								break;
							case 1:
								msgText="GTA";
								sendMessageHandle(msgText);
								break;
							case 2:
								msgText="GTC";
								sendMessageHandle(msgText);
								break;
							case 3:
								msgText="GTF";
								sendMessageHandle(msgText);
								break;
							case 4:
								msgText="GTE";
								sendMessageHandle(msgText);
								break;
							case 8:
								msgText="GTX";
								sendMessageHandle(msgText);
								break;							
							case 5:
							{
								switch(showCount)
								{
								case 0: 
									msgText="GTS";
									sendMessageHandle(msgText);
									break;
								case 1:
									msgText="GTH";
									sendMessageHandle(msgText);
									break;									
								case 2:
									msgText="GTG";
									sendMessageHandle(msgText);
									break;
								case 3:
									msgText="GTI";
									sendMessageHandle(msgText);
									break;
								}
								if(++showCount>3) showCount=0;
							}
						}
					}
					lastPageItem=item;
					//Log.d("===Current Item("+item+")========","OnTimer");				
				}
				else
				{
					if(begincmd)
					{
						msgText="GTJ:"+pswString;
						sendMessageHandle(msgText);
					}
				}
				//
				if(needUpdate)
				{
					manager.showNoticeDialog();
					needUpdate=false;
					updateThis=false;
				}
				if(needReConnect)
				{
					if(mDeviceConnected)
					{
				        //
						DisConnectDevice();
				        hasconnected=false;
				        begincmd=false;
				        bBluetoothLeConnected=false;
				        mDeviceConnected=false;
			        }
					ConnectDevice();
				}
			}
			else
			{
				if(!g_firmwareUpdating && sendrepose==2)
    			{
            		if(bNewFirmware)
    				{
    					msgText="STU:"+mHardwareStr;
    				}
    				else
    				{
    					msgText="STU";
    				}
    				sendMessageHandle(msgText);
    			}
			}
			timerHandler.postDelayed(this, 500);
		}
	};
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN ,WindowManager.LayoutParams.FLAG_FULLSCREEN); 
        setContentView(R.layout.activity_main);
        //保持屏幕唤醒
      	getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //设置触控面板
        //WindowManager.LayoutParams params = getWindow().getAttributes();
        //params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE;
        //getWindow().setAttributes(params);
        mContext=this;
        needReConnect=false;
        bBluetoothLeConnected=false;
        
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),this);

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        //mViewPager.setVerticalScrollBarEnabled(true);    
        //setBluetooth();
        //findRFBmsDevice();
        timerHandler.postDelayed(timerRunnable,1000);
        //
        SharedPreferences settings = getSharedPreferences(BMS_Settings, 0);
        pswString=settings.getString(APP_USER_CODE, "123456");
        updateThis=settings.getBoolean(APP_UPDATETHIS, true);
        if(updateThis)
        {
        	new UpdateThread().start();
        }
        //
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
        }
        // 如果本地蓝牙没有开启，则开启  
        if (mBluetoothAdapter.isEnabled())
        {
        	mDeviceType=settings.getInt(EXTRAS_DEVICE_TYPE, 0);
        	mDeviceAddress=settings.getString(EXTRAS_DEVICE_ADDRESS, "");  
            Log.d("===Connect Device====","Device Addr:"+mDeviceAddress+"DevType:"+mDeviceType);
            ConnectDevice();
        }
        else
        {
            // 我们通过startActivityForResult()方法发起的Intent将会在onActivityResult()回调方法中获取用户的选择，比如用户单击了Yes开启，  
            // 那么将会收到RESULT_OK的结果，  
            // 如果RESULT_CANCELED则代表用户不愿意开启蓝牙  
            Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  
            startActivityForResult(mIntent, RESULT_FIRST_USER);  
        }
        
    }

	protected void sendMessageHandle(String msgText) {
		// TODO Auto-generated method stub
		if(bBluetoothLeConnected)
		{
			mBluetoothLeService.txxx(msgText+"\r\n");
		}
		else
		{
			msgText+="\r\n";
	        if (bltSocket == null)   
	        {  
	            Toast.makeText(mContext, getString(R.string.text_bmsunconected), Toast.LENGTH_SHORT).show();  
	            return;  
	        }
	        try {
	            OutputStream os = bltSocket.getOutputStream();   
	            os.write(msgText.getBytes());  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }
		}
	}
	//
	private Handler LinkDetectedHandler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            //Toast.makeText(mContext, (String)msg.obj, Toast.LENGTH_SHORT).show();
            if(msg.what==1)   
            {
            	String info=(String)msg.obj;
            	if(updatingfirmware)
            	{
	            	if(info.contains("DTU"))
	            	{
	            		//update
	            		g_firmwareUpdating=true;
	            		sendrepose=0;
	            		firmwareUpdateTrhead.start();
	            	}
	            	else if(info.equals("AG"))
	            	{
	            		sendrepose=2;
	            	}
	            	else if(info.equals("OK"))
	            	{
	            		sendrepose=1;
	            	}
	            	else if(info.equals("ER"))
	            	{
	            		sendrepose=3;
	            		g_firmwareUpdating=false;
	            		updatingfirmware=false;
	            		mUpdateFirmDialog.dismiss();
	            		Toast.makeText(MainActivity.this, getString(R.string.text_dataerrtips), Toast.LENGTH_LONG).show();
	            	}
            	}
            	else
            	{
	            	if(hasconnected)
	            	{
		            	//接收来自蓝牙的消息，解析文本消息
		                //msgList.add((String)msg.obj); 
		                //Toast.makeText(MainActivity.this, (String)msg.obj, Toast.LENGTH_LONG).show();
		            	int item=mViewPager.getCurrentItem();
						PagerAdapter adapter=mViewPager.getAdapter();
						DummySectionFragment fragment=(DummySectionFragment) ((SectionsPagerAdapter) adapter).getFragment(item);
						fragment.UpdateView(item,msg);
						//Toast.makeText(MainActivity.this, (String)msg.obj, Toast.LENGTH_LONG).show();
						//Log.d("=====HandleMessage====","PageItem("+item+"),msg:"+(String)msg.obj);
	            	}
	            	else
	            	{
	            		if(info.contains("="))
	            		{
		            		String[] cmdStr=info.split("=");
		            		if(cmdStr[0].equals("J"))
		            		{
		            			String[] infoStr=cmdStr[1].split(",");
		            			if(infoStr[0].equals("OK"))
		            			{
		            				//g_bEnableResetBMS=false; 
		            				g_bSupportPsw=true;
		            				Toast.makeText(MainActivity.this, getString(R.string.text_pswok), Toast.LENGTH_LONG).show();
		            			}
		            			else
		            			{
		            				Toast.makeText(MainActivity.this, getString(R.string.text_pswerr), Toast.LENGTH_LONG).show();
		            				g_bSupportPsw=false;
		            			}
		            			hasconnected=true;
		            		}
		            		else if(cmdStr[1].equals("ERC"))
		            		{
		            			//support old version
		            			hasconnected=true;
		            			g_bSupportPsw=false;
		            		}
	            		}
	            	}
            	}
            } 
            else
            {
            	if(msg.what==0)
            	{
            		//连接成功
            		begincmd=true;
					//String msgText="GTA"; 
					//sendMessageHandle(msgText);
            	}
                //msgList.add((String)msg.obj);
            	Toast.makeText(MainActivity.this, (String)msg.obj, Toast.LENGTH_LONG).show();
            }
            //mAdapter.notifyDataSetChanged();  
            //mListView.setSelection(msgList.size() - 1); 
        }  
    };
	//开启客户端  
    private class clientThread extends Thread {           
        @Override  
        public void run() {  
        	if(bBluetoothLeConnected)
        	{
                registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
                if (mBluetoothLeService != null) {
                	  
                    final boolean result = mBluetoothLeService.connect(mDeviceAddress);
                    Log.d(TAG, "Connect request result=" + result);
                }
        	}
        	else
        	{
	            try {  
	                //创建一个Socket连接：只需要服务器在注册时的UUID号  
	                // socket = device.createRfcommSocketToServiceRecord(BluetoothProtocols.OBEX_OBJECT_PUSH_PROTOCOL_UUID);  
	            	bltSocket = bltDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));  
	                bltSocket.connect();
	                //启动接受数据  
	                mreadThread = new readThread();  
	                mreadThread.start(); 
	                //
		            Message msg = new Message();  
		            msg.obj = getString(R.string.text_bmsconected);
		            msg.what = 0;  
		            LinkDetectedHandler.sendMessage(msg); 	                
	            }   
	            catch (IOException e)   
	            {  
	                Log.e("connect", "NOT CONNECT BLUTOOTH2.0", e);  
	                Message msg = new Message();  
	                msg.obj = getString(R.string.text_bmsnotfound);  
	                msg.what = -2;  
	                LinkDetectedHandler.sendMessage(msg);  
	                //scanLeDevice(true);
	            }
        	}
        }  
    };  

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }
    
  //读取数据  
    private class readThread extends Thread {   
        @Override  
        public void run() {  
              
            byte[] buffer = new byte[1024];  
            int bytes;
            byte[] buf_data = new byte[288];
            int n=0;
            InputStream mmInStream = null;  
              
            try {  
                mmInStream = bltSocket.getInputStream();  
            } catch (IOException e1) {  
                // TODO Auto-generated catch block  
                e1.printStackTrace();  
            }
            needReConnect=false;
            while (true) {  
                try {  
                    // Read from the InputStream  
                    if( (bytes = mmInStream.read(buffer)) > 0 )  
                    {  
                        for(int i=0; i<bytes; i++)  
                        {
                            buf_data[n++] = buffer[i];
                        	if(n>2 && buf_data[n-1]=='\n' && buf_data[n-2]=='\r')
                        	{
                        		buf_data[n]='\0';
		                        String s = new String(buf_data);
		                        Message msg = new Message();
		                        msg.obj = s.substring(0, n-2);
		                        msg.what = 1;
		                        LinkDetectedHandler.sendMessage(msg);
		                        //buf_data = new byte[256];
		                        n=0;
                        	}
                        }
                    }
                } catch (IOException e) {  
                    try {  
                        mmInStream.close();  
                    } catch (IOException e1) {  
                        // TODO Auto-generated catch block  
                        e1.printStackTrace();  
                    }
                    //Toast.makeText(MainActivity.this, getString(R.string.text_bmsunconected), Toast.LENGTH_LONG).show();
                    needReConnect=true;
                    break;  
                }
            }  

        }  
    }
    private void DisConnectDevice()
    {
         //
        if(bBluetoothLeConnected)
        {
        	unregisterReceiver(mGattUpdateReceiver);
        	unbindService(mServiceConnection); 
        	bBluetoothLeConnected=false;
        }
        //else
        {
        	if(clientConnectThread!=null)  
            {  
                clientConnectThread.interrupt();  
                clientConnectThread= null;  
            }  
            if(mreadThread != null)  
            {  
                mreadThread.interrupt();  
                mreadThread = null;  
            }  
            if (bltSocket != null) {  
                try {  
                	bltSocket.close();  
                } catch (IOException e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                }  
                bltSocket = null;  
            }
        	//shutdownClient();
        }
    }
    //
	private void ConnectDevice()
	{
		/*
		if(mDeviceConnected){
	        //
			DisConnectDevice();
	        hasconnected=false;
	        begincmd=false;
	        bBluetoothLeConnected=false;
	        mDeviceConnected=false;
        }*/
		if(mBluetoothAdapter.isEnabled())
		{
			if(mDeviceType==2)
	        {
	        	//BLE
	            needReConnect=false;    				
	    		if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
	                Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
	            }
	    		else
	    		{
	            	Intent gattServiceIntent = new Intent(mContext, BluetoothLeService.class);
	                boolean sg = bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
	                if(!sg) Toast.makeText(this, R.string.ble_bind_error, Toast.LENGTH_SHORT).show();
	                //mDeviceConnected=true;
	    		}
	        }
	    	else if(mDeviceType>0)
	    	{
	        	if(!mDeviceAddress.isEmpty())
	        	{
	        		bltDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
	        		clientConnectThread = new clientThread();  
	        		clientConnectThread.start();
	        		mDeviceConnected=true;
	        	}
	    	}
		}
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if(mDeviceConnected){   
	        //
	        DisConnectDevice();
	        hasconnected=false;
	        begincmd=false;
	        bBluetoothLeConnected=false;
	        mDeviceConnected=false;
		}
        timerHandler.removeCallbacks(timerRunnable);
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		super.onDestroy();
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
        /*
		//注册蓝牙接收广播  
        if(!hasregister){  
            hasregister=true;  
            //IntentFilter filterStart=new IntentFilter(BluetoothDevice.ACTION_FOUND);      
            //IntentFilter filterEnd=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);      
            //registerReceiver(mydevice, filterStart);  
            //registerReceiver(mydevice, filterEnd); 
            
	        //setBluetooth();
	        //findRFBmsDevice();  
        }
        */
		//ConnectDevice();
		super.onStart();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		SharedPreferences settings = getSharedPreferences(BMS_Settings, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean(APP_UPDATETHIS,updateThis);
		editor.putInt(EXTRAS_DEVICE_TYPE, mDeviceType);
		editor.putString(EXTRAS_DEVICE_ADDRESS, mDeviceAddress);
		editor.putString(APP_USER_CODE, pswString);
		editor.commit();
		super.onStop();
		//DisConnectDevice();
		/*
		if(hasconnected)
		{
			String msgText="ST"; 
			sendMessageHandle(msgText);
		}*/
	}
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    @Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
    	int i=item.getOrder();
    	switch(i)
    	{
    	case 100:
     		retUpdate=false;
    		new UpdateThread().start();
    		while(!retUpdate);
			if(!needUpdate)
			{
				Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show();
			}   		
    		break;
    	case 200:
    		try {
				String verName = getPackageManager().getPackageInfo("com.deva.bletest", 0).versionName;
				Toast.makeText(mContext, "Current Version "+verName, Toast.LENGTH_LONG).show();
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}    		
    		break;
    	case 300:
    	{
    		Intent intent=new Intent();
    		intent.setClass(this,FileSelectActivity.class);
    		intent.putExtra("CurrentPath",Environment.getExternalStorageDirectory().getPath());
    		startActivityForResult(intent,0);
    	}
    		break;
    	case 400:
    	{
    		Intent intent=new Intent();
    		intent.setClass(this,DeviceScanActivity.class);
    		startActivityForResult(intent,0);
    	}
    		break;
    	case 500:
    	{
    		AlertDialog.Builder builder = new Builder(this);
			builder.setTitle(getString(R.string.text_verifycode));
			//builder.setMessage("您确定需要修改参数？");
			final LayoutInflater inflater = LayoutInflater.from(this);
			View v = inflater.inflate(R.layout.password_input, null);
			mPassword = (EditText) v.findViewById(R.id.pswEditText);
			mPassword.setText(pswString);
			builder.setView(v);
    		builder.setPositiveButton(getString(R.string.text_ok), new DialogInterface.OnClickListener(){

    			@Override
    			public void onClick(DialogInterface arg0, int arg1) {
    				pswString=mPassword.getText().toString();
					sendMessageHandle("GTJ:"+pswString);
					hasconnected=false;
    			}
    		});
    		builder.setNegativeButton(getString(R.string.text_cancel), new DialogInterface.OnClickListener(){

    			@Override
    			public void onClick(DialogInterface arg0, int arg1) {
    				// TODO Auto-generated method stub
    				
    			}	
    		});
    		builder.show();
    	}
    		break;
    	}
    	Log.d("onmenuitem","press item:"+featureId+",order:"+item.getOrder());
    	//mViewPager.setCurrentItem(2,true);
		return super.onMenuItemSelected(featureId, item);
	}
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(resultCode==1)
		{
			updatingfirmware=true;
			g_firmwareUpdating=true;
			mFirmWareFilePath=data.getStringExtra("CurrentPath");
            AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);  
            dialog.setTitle(getString(R.string.action_firmwareupdate));  
            dialog.setMessage(getString(R.string.text_tipsupdatefirmware)+mFirmWareFilePath);  
            dialog.setPositiveButton(getString(R.string.text_ok), new OnClickListener()
    		{
    			@Override
    			public void onClick(DialogInterface dialog, int which)
    			{
    				FileInputStream in = null;
    				String msgText;
    				String tmpStr="";
    				dialog.dismiss();
    				//File f=new File(mFirmWareFilePath);
    				try 
    				{
    					byte[] tempbytes = new byte[10]; 
    					in = new FileInputStream(mFirmWareFilePath);
    					if(in.read(tempbytes) != -1){
    						tmpStr=new String(tempbytes,0,4);
    					}
    				}
    				catch (Exception e1)
    				{
    					e1.printStackTrace();
    				}
    				finally
    				{
    					if (in != null)
    					{
    						try {
    							in.close(); 
    						} 
    						catch (IOException e1) {
    					
    						} 
    					
    					}
    				}
    				if(tmpStr.length()==4 && (tmpStr.charAt(0)=='D' || tmpStr.charAt(0)=='H'))
    				{
    					mHardwareStr=tmpStr;
    					bNewFirmware=true;
    					msgText="STU:"+tmpStr;
    				}
    				else
    				{
    					bNewFirmware=false;
    					msgText="STU";
    				}
					sendMessageHandle(msgText);
					//
    				sendrepose=0;
					showUpdateFirmDialog();
    			}
    		});
            dialog.setNegativeButton(getString(R.string.text_quit),
                    new DialogInterface.OnClickListener() {  
                        @Override  
                        public void onClick(DialogInterface dialog, int which) { 
                			updatingfirmware=false;
                			g_firmwareUpdating=false;
                        	dialog.dismiss();
                        }  
                    });  
            dialog.show();
	        //Toast.makeText(this, R.string.nobitmaps, Toast.LENGTH_LONG).show();
		}
		else if(resultCode==2)
		{
			mDeviceType=data.getIntExtra(EXTRAS_DEVICE_TYPE, 0);
			mDeviceAddress=data.getStringExtra(EXTRAS_DEVICE_ADDRESS);
			Log.d("===Connect Device====","Device Addr:"+mDeviceAddress+"DevType:"+mDeviceType);
			if(mDeviceConnected)
			{
		        //
				DisConnectDevice();
		        hasconnected=false;
		        begincmd=false;
		        bBluetoothLeConnected=false;
		        mDeviceConnected=false;
	        }
			ConnectDevice();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	protected void showUpdateFirmDialog() {
		// TODO Auto-generated method stub
		// 鏋勯�犺蒋浠朵笅杞藉璇濇
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle(R.string.firmware_updating);
		// 缁欎笅杞藉璇濇澧炲姞杩涘害鏉�
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.softupdate_progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
		builder.setView(v);
		// 鍙栨秷鏇存柊
		/*
		builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				updatingfirmware=false;
				dialog.dismiss();
			}
		});
		*/
		mUpdateFirmDialog = builder.create();
		mUpdateFirmDialog.setCancelable(false);		
		mUpdateFirmDialog.show();
		//
		firmwareUpdateTrhead=new UpdateFirmwareThread();
		
	}
	//
	public static byte[] getByteArr(byte[]data,int start ,int end){
		byte[] ret=new byte[end-start];
		for(int i=0;(start+i)<end;i++){
			ret[i]=data[start+i];
		}
		 return ret;
	}
	//
	private class UpdateFirmwareThread extends Thread
	{
		@Override
		public void run()
		{
			FileInputStream in = null;
			g_firmwareUpdating=true;
			File f=new File(mFirmWareFilePath);
			if(f.exists())
			{
				Date curDate,endDate;
				byte[] subbytes=new byte[20];
				long length=f.length();
				try 
				{
					//System.out.println("以字节为单位读取文件内容，一次读多个字节："); 
					//一次读多个字节 
					byte[] tempbytes = new byte[1024]; 
					int byteread = 0;
					int count=0;
					long wraddr=0;
					in = new FileInputStream(mFirmWareFilePath);
					if(bNewFirmware)
					{
						//略过开头4字节
						in.read(tempbytes,0,4);
					}
					//ReadFromFile.showAvailableBytes(in);
					//读入多个字节到字节数组中，byteread为一次读入的字节数 
					while ((byteread = in.read(tempbytes)) != -1){
						//System.out.write(tempbytes, 0, byteread);
						int nb;
						byte checkout=0;
						for(int i=0;i<byteread;i++)
						{
							checkout+=tempbytes[i];
						}
						if(byteread%20==0)
						{
							nb=byteread/20;
						}
						else
						{
							nb=byteread/20+1;
						}
						//
						subbytes[0]=(byte) 0xA5;
						subbytes[1]=(byte) 0xA5;
						subbytes[2]=(byte) nb;
						subbytes[3]=(byte) (nb>>8);
						subbytes[4]=(byte) byteread;
						subbytes[5]=(byte) (byteread>>8);
						subbytes[6]=(byte) checkout;
						subbytes[7]=(byte) 0;
						subbytes[8]=(byte) wraddr;
						subbytes[9]=(byte) (wraddr>>8);
						subbytes[10]=(byte) (wraddr>>16);
						subbytes[11]=(byte) (wraddr>>24);
						//
						sendrepose=0;
						while(sendrepose!=1)
						{
							
							sendtobytes(subbytes);
							sendrepose=0;
							curDate = new Date(System.currentTimeMillis());
							while(sendrepose==0)
							{
								endDate = new Date(System.currentTimeMillis());
								long diff = endDate.getTime() - curDate.getTime();
								if(diff>5000)
								{
									//超时
									updatingfirmware=false;
									mUpdateFirmDialog.dismiss();
									return ;
								}
							}
//							if(sendrepose==3)
//							{
//								//超时或出错
//								updatingfirmware=false;
//								mUpdateFirmDialog.dismiss();
//								return ;
//							}
						}
						//
						do{
							sendrepose=0;
							for(int i=0;i<nb;i++)
							{
								//subbytes=getByteArr(tempbytes,i*20,(i+1)*20-1);
								for(int j=0;j<20;j++)
								{
									if((j+i*20)<byteread)
									{
										subbytes[j]=tempbytes[j+i*20];
									}
									else
									{
										subbytes[j]=0;
									}
								}
								sendtobytes(subbytes);
								Thread.sleep(10);
							}
							//
							curDate = new Date(System.currentTimeMillis());
							while(sendrepose==0)
							{
								endDate = new Date(System.currentTimeMillis());
								long diff = endDate.getTime() - curDate.getTime();
								if(diff>6000)
								{
									//超时
									updatingfirmware=false;
									mUpdateFirmDialog.dismiss();
									return ;
								}
							}
//							if(sendrepose==3)
//							{
//								//超时或出错
//								updatingfirmware=false;
//								mUpdateFirmDialog.dismiss();
//								return ;
//							}
						}while(sendrepose!=1);
						//
						wraddr+=byteread;
						count+=byteread;
						// 璁＄畻杩涘害鏉′綅缃�
						progress = (int) (((float) count / length) * 100);
						// 鏇存柊杩涘害
						mUpdateFirmHandler.sendEmptyMessage(FIRMDOWNLOAD);
					}
					//完成
					subbytes[0]=(byte) 0x55;
					subbytes[1]=(byte) 0x55;
					//
					sendrepose=0;
					while(sendrepose!=1)
					{
						sendtobytes(subbytes);
						sendrepose=0;
						curDate = new Date(System.currentTimeMillis());
						while(sendrepose==0)
						{
							endDate = new Date(System.currentTimeMillis());
							long diff = endDate.getTime() - curDate.getTime();
							if(diff>4000)
							{
								//超时
								updatingfirmware=false;
								mUpdateFirmDialog.dismiss();
								return;
							}
						}
//						if(sendrepose==3)
//						{
//							//超时或出错
//							updatingfirmware=false;
//							mUpdateFirmDialog.dismiss();
//							return ;
//						}
					}
					g_firmwareUpdating=false;
					mUpdateFirmHandler.sendEmptyMessage(FIRMDOWNLOAD_FINISH);
				}
				catch (Exception e1)
				{
					e1.printStackTrace(); 	
				}
				finally
				{
					if (in != null)
					{
						try {
							in.close(); 
						} 
						catch (IOException e1) {
					
						} 
					
					} 	
				}
			}
			// 鍙栨秷涓嬭浇瀵硅瘽妗嗘樉绀�
			updatingfirmware=false;
			mUpdateFirmDialog.dismiss();
		}

		private void sendtobytes(byte[] subbytes) {
			// TODO Auto-generated method stub
			if(bBluetoothLeConnected)
			{
				mBluetoothLeService.txbytes(subbytes);
			}
			else
			{
		        if (bltSocket == null)
		        {
		            Toast.makeText(mContext, getString(R.string.text_bmsunconected), Toast.LENGTH_SHORT).show();  
		            //mUpdateFirmDialog.dismiss();
		            return;
		        }
		        try {
		            OutputStream os = bltSocket.getOutputStream();   
		            os.write(subbytes);  
		        } catch (IOException e) {  
		            e.printStackTrace();  
		        }
			}
		}
	}
	//
	private Handler mUpdateFirmHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
			// 姝ｅ湪涓嬭浇
			case FIRMDOWNLOAD:
				// 璁剧疆杩涘害鏉′綅缃�
				mProgress.setProgress(progress);
				break;
			case FIRMDOWNLOAD_FINISH:
				// 瀹夎鏂囦欢
				//installApk();
				
				break;
			default:
				break;
			}
		};
	};
	//
	private class UpdateThread extends Thread{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			if (manager.isUpdate())
			{
				// 鏄剧ず鎻愮ず瀵硅瘽妗�
				//manager.showNoticeDialog();
				needUpdate=true;
			}
			else
			{
				needUpdate=false;
			}
			retUpdate=true;
			//Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show();
    		//manager.checkUpdate();
		}
		
	}
}
